import React from 'react';
import { Button, Balloon, Progress } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import { ENUM } from 'utils/constants';
import TableCellOverlay from 'components/importProjectListModal/overlay1';
import TableSection from './table';
import ListLoading from 'atComponents/ListLoading';
import track from 'utils/track';
import './index.scss';
import intl from '../../../../locale';
import { navigateOpen } from 'utils/router';

const prefix = 'upgrade-step3';
const progressPage = 'upgrade_completed';

const visiblityLevelObj = {
  0: intl.get({
    id: 'code-assets.containers.progress.PrivateVisibleOnlyToMembers',
    defaultMessage: '私有(仅代码库成员可见)',
  }),
  10: intl.get({
    id: 'code-assets.containers.progress.VisibleToEnterpriseAccessibleTo',
    defaultMessage: '企业可见(企业内成员可访问)',
  }),
};

export default class ProgressStep extends React.Component {
  upgradeTimer = null;

  isUnmount = false;

  componentDidMount() {
    this.openTimer();
    this.props.updateData({
      upgrading: true,
    });
  }

  openTimer = () => {
    if (this.isUnmount) {
      return;
    }

    this.upgradeTimer = setInterval(() => {
      this.props.getLastRecord();
    }, 5000);
  };

  componentDidUpdate() {}

  componentWillUnmount() {
    clearInterval(this.upgradeTimer);
    this.isUnmount = true;
  }

  goNext = () => {
    this.props.updateData({
      curStep: 2,
    });
  };

  renderOriginalVisibilityLevel = (value) => {
    return <div style={{ padding: '0 8px' }}>{ENUM.visibility_level_text[value]}</div>;
  };

  renderImportRepoName = (value, index, record) => {
    const trigger = (
      <div className="table-cell-one-line">
        <a href={record.original_repo_path} target="_blank" rel="noreferrer">
          {value}
        </a>
      </div>
    );

    return (
      <Balloon.Tooltip trigger={trigger} align="t">
        {value}
      </Balloon.Tooltip>
    );
  };

  renderTargetVisibilityLevel = (value) => {
    return <div style={{ padding: '0 8px' }}>{visiblityLevelObj[value]}</div>;
  };

  isInvalidRecord = (repeatList, original_project_id) => {
    return (
      repeatList.findIndex((item) => {
        return item.id === original_project_id;
      }) > -1
    );
  };

  // 所有数据均可编辑
  renderNewImportName = (value, index, record) => {
    const { repeatList } = this.props;
    const isRepeat = this.isInvalidRecord(repeatList, record.original_project_id);
    const invalidInfo = repeatList.find((item) => {
      return item.id === record.original_project_id;
    });
    return (
      <TableCellOverlay
        visibility_level={record.target_visibility_level}
        value={value}
        invalidInfo={invalidInfo}
        isRepeat={isRepeat}
        import_repo_id={record.import_repo_id}
        saveName={this.saveName}
      />
    );
  };

  onPageChange = (value, type) => {
    const defaultLastRecordPage = {
      CREATED: 1,
      UNKNOWN_FAILED: 1,
      SUCCESS: 1,
    };

    this.props.getLastRecord({
      ...defaultLastRecordPage,
      [type]: value,
    });
  };

  goRecord = () => {
    this.props.updateData({
      pageType: 'records',
    });
  };

  goStep0 = () => {
    track({
      action: 'upgrade_again',
      page: progressPage,
    });

    this.props.updateData({
      curStep: 0,
    });
  };

  goCodeup = () => {
    track({
      action: 'go_codeup',
      page: progressPage,
    });

    navigateOpen('/', '_blank');
  };

  render() {
    const {
      lastRecord,
      lastUpgradeLoaded,
      organizations,
      selectedOrganizationId,
      isLoadingProgress,
      upgrading,
    } = this.props;
    const curOrganization =
      organizations.find((item) => item.organization_id === selectedOrganizationId) || {};
    const {
      CREATED: createRecord,
      UNKNOWN_FAILED: failRecord,
      SUCCESS: successRecord,
    } = lastRecord;
    const createdLength = createRecord.pageInfo ? createRecord.pageInfo.total : 0;
    const failLength = failRecord.pageInfo ? failRecord.pageInfo.total : 0;
    const successLength = successRecord.pageInfo ? successRecord.pageInfo.total : 0;
    const percent = Number(
      (
        ((successLength + failLength) / (failLength + successLength + createdLength || 1)) *
        100
      ).toFixed(0),
    );

    if (isLoadingProgress) {
      return (
        <div style={{ marginTop: 100 }}>
          <ListLoading />
        </div>
      );
    }

    if (percent === 100) {
      clearInterval(this.upgradeTimer);
    }

    if (upgrading && percent === 100) {
      this.props.updateData({
        upgrading: false,
      });
    }

    return (
      <div className={`${prefix}`}>
        <div className={`${prefix}-top`}>
          <div className={`${prefix}-top-left`}>
            {percent === 100 ? (
              <YunxiaoIcon type="success-fill" className={`${prefix}-top-left-icon success`} />
            ) : (
              <YunxiaoIcon
                type="avatar-status-message-fill"
                className={`${prefix}-top-left-icon creating`}
              />
            )}
          </div>
          <div className={`${prefix}-top-right`}>
            <div className={`${prefix}-top-right-title`}>
              {' '}
              {percent === 100
                ? intl.get({
                    id: 'code-assets.containers.progress.UpgradeCompleted',
                    defaultMessage: '升级完成',
                  })
                : intl.get({
                    id: 'code-assets.containers.progress.Upgrade',
                    defaultMessage: '升级中',
                  })}
            </div>
            <div className={`${prefix}-top-right-desc`}>
              {percent === 100
                ? intl.get({
                    id: 'code-assets.containers.progress.UpgradedToEnterprise',
                    defaultMessage: '已升级至企业',
                  })
                : intl.get({
                    id: 'code-assets.containers.progress.UpgradingToEnterprise',
                    defaultMessage: '正在升级至企业',
                  })}{' '}
              「{curOrganization.organization_name || ''}」
            </div>
            {percent === 100 ? (
              <div className={`${prefix}-top-right-success`}>
                <Button type="primary" style={{ marginRight: 8 }} onClick={this.goCodeup}>
                  {intl.get({
                    id: 'code-assets.containers.progress.ToNewVersion',
                    defaultMessage: '前往新版',
                  })}
                </Button>
                <Button type="normal" style={{ marginRight: 8 }} onClick={this.goStep0}>
                  {intl.get({
                    id: 'code-assets.containers.progress.ContinueToUpgrade',
                    defaultMessage: '继续升级',
                  })}
                </Button>
              </div>
            ) : (
              <div className={`${prefix}-top-right-progress`}>
                <Progress percent={percent} size="large" />
              </div>
            )}
          </div>
        </div>
        <div className={`${prefix}-table`}>
          <div className={`${prefix}-table-success`}>
            <TableSection
              {...{
                list: successRecord.list,
                lastUpgradeLoaded,
                tablePagination: successRecord.pageInfo,
                onPageChange: (page) => {
                  this.onPageChange(page, 'SUCCESS');
                },
                dataType: 'success',
              }}
            />
          </div>
          <div className={`${prefix}-table-split-line`} />
          <div className={`${prefix}-table-fail`}>
            <TableSection
              {...{
                list: failRecord.list,
                isLoadingTable: !lastUpgradeLoaded,
                tablePagination: failRecord.pageInfo,
                onPageChange: (page) => {
                  this.onPageChange(page, 'UNKNOWN_FAILED');
                },
                dataType: 'fail',
              }}
            />
          </div>
        </div>
      </div>
    );
  }
}
